﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TorBrowserUpdater
{
    public class TBBVersionComparer
    {

        /// <summary>
        /// Returns True if versionToCompare is newer than otherVersion.
        /// Both versions must follow the pattern of 3 numbers separated by a dot, followed by a hyphen and a last number.
        /// </summary>
        /// <param name="versionToCompare"></param>
        /// <param name="otherVersion"></param>
        /// <returns></returns>
        public static bool IsVersionNewer(string versionToCompare, string otherVersion)
        {
            string[] versionParts1 = versionToCompare.Split('-', '.');
            string[] versionParts2 = otherVersion.Split('-', '.');

            if(versionParts1.Length == 0)
                throw new ArgumentException("Argument versionToCompare is not a valid version string.");
            if (versionParts2.Length == 0)
                throw new ArgumentException("Argument otherVersion is not a valid version string.");

            int i = 0;
            while(i < versionParts1.Length && i < versionParts2.Length)
            {
                int versionNumber1;
                int versionNumber2;

                if(!int.TryParse(versionParts1[i], out versionNumber1))
                {
                    if (versionParts1[i] == "beta" || versionParts1[i].StartsWith("pt"))
                    {
                        i++;
                        continue;
                    }
                    throw new ArgumentException("Argument versionToCompare is not a valid version string.");
                }

                if(!int.TryParse(versionParts2[i], out versionNumber2))
                {
                    if (versionParts1[i] == "beta" || versionParts1[i] == "pt1")
                    {
                        i++;
                        continue;
                    }
                    throw new ArgumentException("Argument otherVersion is not a valid version string.");
                }

                if(versionNumber1 != versionNumber2)
                    return (versionNumber1 > versionNumber2);

                i++;
            }
            return false;
        }

    }
}
